
#include <stdint.h>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include "BSP.h"
#include "Util.h"
#include "Debug.h"
#include "QrHN.h"
#include "Env.h"

static uint8_t qrRxBuffer[300];
static uint16_t qrRxLength;
static int qrRxTime;
static int qrLife;
static int qrSNTime;
static uint32_t qrSN;
uint8_t qrLen;
uint8_t qrData[128];

static void Qr_RxCallback(uint8_t rx){
	if(qrRxLength < (sizeof(qrRxBuffer)-1)){
		qrRxBuffer[qrRxLength++] = rx;
		qrRxTime = 5;
	}
}

void Reader_Qr_RxTick(void){
	if(qrLife){
		qrLife--;
		if(qrLife == 0){
			qrRxLength = 0;
		}
	}
	
	if(qrRxTime > 0){
		qrRxTime--;
		if(qrRxTime == 0){
			qrLife = 1000;
		}
	}
	
	if(qrSNTime > 0){
		qrSNTime--;
	}
}

void Reader_QR_Init(void){
	qrRxLength = 0;
	qrRxTime = -1;
	BSP_Uart_SetRxCallback(4, Qr_RxCallback);
}

int Reader_Qr_ReadCardNo(char* qr, uint32_t* no){
	char* cardNo = strstr((const char*)qr, "\"cardNo\":\"");
	if(cardNo){
		sscanf(cardNo, "\"cardNo\":\"%u\"", no);
		return 0;
	}
	return -1;
}

#if 0
/*
”cardNo”:”971019019”
*/
int Reader_QR_Read(uint8_t *sn){
	if(qrRxTime == 0){
		qrRxTime = -1;
		if(qrRxLength == 0){
			return -1;
		}
		qrRxBuffer[qrRxLength] = 0;
		DBG_WRITE("qr: ");
		DBG_WRITE((const char*)qrRxBuffer);
		uint32_t tampSN = 99999999;
#if 1
		char* cardNo = strstr((const char*)qrRxBuffer, "\"cardNo\":\"");
		if(cardNo){
			sscanf(cardNo, "\"cardNo\":\"%u\"", &tampSN);
		}
#endif 
		qrRxLength = 0;
		if(tampSN == qrSN && qrSNTime > 0){
			return 0;
		}
		Mem_Reverse_Copy(sn, (uint8_t*)&tampSN, sizeof(tampSN));
		qrSN = tampSN;
		qrSNTime = 1000;
		return 4;
	}
	
	return -1;
}
#endif 

int Reader_QR_Read(uint8_t *sn, uint8_t* nlen){
	if(qrRxTime == 0){
		qrRxTime = -1;
		if(qrRxLength == 0){
			return QR_ERR_LEN;
		}
		qrRxBuffer[qrRxLength] = 0;
		DBG_WRITE("qr: ");
		DBG_WRITE((const char*)qrRxBuffer);
		if(envData.qrWorkMode == ENV_Qr_WorkMode_HNEncrypt){
			uint8_t tmpSN[128];
			uint8_t tlen = 0;
			int ret = HN_Qr_Proc(qrRxBuffer, qrRxLength, tmpSN, &tlen);
			if(ret){
				return ret;
			}
			
			qrRxLength = 0;
			
			if(tlen == qrLen && memcmp(tmpSN, qrData, tlen) == 0 && qrSNTime > 0){
				return QR_S_NONE;
			}
			
			memcpy(qrData, tmpSN, tlen);
			qrLen = tlen;
			
			*nlen = tlen;
			memcpy(sn, tmpSN, tlen);
			
			qrSNTime = 1000;
		}
		else
		if(envData.qrWorkMode == ENV_Qr_WorkMode_Bridges){
			
			if(qrRxLength > 2 && memcmp(qrRxBuffer, "-s", 2) == 0){
				uint16_t clen = qrRxLength - 2;
				qrRxLength = 0;
				return Qr_ReceiveCommand(qrRxBuffer + 2, clen);
			}
			memcpy(sn, qrRxBuffer, qrRxLength);
			*nlen = qrRxLength;
			qrRxLength = 0;
		}
		else{
			return QR_S_NONE;
		}
		
		return QR_S_SUCCESS;
	}
	
	return QR_S_NONE;
}




